package com.loop.unclelend.ui.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.loop.unclelend.R
import com.loop.unclelend.base.app.AppStackManager
import com.loop.unclelend.base.app.ForegroundBackgroundHelper
import com.loop.unclelend.base.app.ForegroundBackgroundObserver
import com.loop.unclelend.databinding.UiMainBinding
import com.loop.unclelend.pro.ProActivity
import com.loop.unclelend.pro.ProFragment
import com.loop.unclelend.ui.adapter.Adapter_MainTab
import com.loop.unclelend.ui.fragment.Fm_Menu
import com.loop.unclelend.ui.presenter.Pre_Main
import com.loop.unclelend.ui.view.IView_Main
import com.loop.unclelend.utils.adapter.UncleOnItemChildClickListener
import com.loop.unclelend.utils.event.UncleEventData
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.log.UncleLog
import org.json.JSONObject

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/5 15:51
 * @Annotation：主页
 */
class Act_Main: ProActivity(),IView_Main {
    lateinit var binding: UiMainBinding
    var presenter: Pre_Main? = null

    private var tabAdapter: Adapter_MainTab? = null

    private var fragmentManager: FragmentManager? = null
    private var curtFragment = Fragment()

    override fun getUncleRootView(): View? {
        binding = UiMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initUncleView() {
        setBackExit(true)

        addUncleMenuFragment()
        initRecyclerView()
        ForegroundBackgroundHelper.addObserve(onForegroundBackgroundObserver)
    }

    override fun initUncleListener() {

    }

    override fun initUncleData() {
        presenter = Pre_Main(this)
        presenter!!.loadUncleMainTabList()
        presenter!!.loadUncleMainFragmentList()
    }

    /**
     * 初始化Tab列表
     */
    private fun initRecyclerView() {
        binding.rvTab.layoutManager = GridLayoutManager(getContext(), 2)
        tabAdapter = Adapter_MainTab(binding.rvTab)
        binding.rvTab.adapter = tabAdapter
        binding.rvTab.itemAnimator = DefaultItemAnimator()
        tabAdapter!!.setOnItemChildClickListener(UncleOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.layout_item) {//切换item
                presenter!!.setUncleCurrentItemIndex(position)
            }
        })
    }

    override fun showUncleTabList(tabList: ArrayList<JSONObject>) {
        tabAdapter!!.data = tabList
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun notifyUncleTabDataChanged() {
        tabAdapter!!.notifyDataSetChanged()
    }

    override fun showUncleFragment(fragment: ProFragment, index: Int) {
        if (fragmentManager == null) {
            fragmentManager = supportFragmentManager
        }
        val transaction = fragmentManager!!.beginTransaction()
        //如果之前没有添加过
        if (!fragment.isAdded) {
            //第三个参数为添加当前的fragment时绑定一个tag
            transaction.hide(curtFragment).add(R.id.layout_content, fragment, "$index")
        } else {
            transaction.hide(curtFragment).show(fragment)
        }
        curtFragment = fragment
        transaction.commitAllowingStateLoss()

        if (index == 1){//实时刷新待还款列表
            publishEventData(UncleEventData(UncleEventData.TYPE.UNCLE_LOAN_REPAY_REFRESH))
        }
    }

    /**
     * 展示个人中心
     */
    fun showUncleMenuFragment(eventRemark: String){
        val isOpen = binding.layoutDrawer.isDrawerOpen(GravityCompat.START)
        if (isOpen){//是否打开
            binding.layoutDrawer.closeDrawer(GravityCompat.START,true)
        } else {
            binding.layoutDrawer.openDrawer(GravityCompat.START,true)
        }
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER,eventRemark)
    }

    /**
     * 添加侧边菜单
     */
    private fun addUncleMenuFragment(){
        if (fragmentManager == null) {
            fragmentManager = supportFragmentManager
        }
        fragmentManager!!
            .beginTransaction()
            .add(R.id.layout_menu, Fm_Menu(binding.layoutDrawer)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * 前后台切换监听
     */
    private val onForegroundBackgroundObserver = object : ForegroundBackgroundObserver {
        override fun foregroundBackgroundNotify(isForeground: Boolean) {
            UncleLog.e("uncle loan main background>>>>>>>>>$isForeground")
            //从桌面进入前台，需要刷新总流程
            if (isForeground) {
//                publishEventData(UncleEventData(UncleEventData.TYPE.UNCLE_PROCESS_REFRESH))
            }
        }
    }

    override fun onUncleEvent(event: UncleEventData) {
        super.onUncleEvent(event)
        when(event.eventType){
            UncleEventData.TYPE.UNCLE_SHOW_HOME -> {
                AppStackManager.finishAllActivity(Act_Main::class.java)
                presenter!!.setUncleCurrentItemIndex(0)
            }
            UncleEventData.TYPE.UNCLE_SHOW_REPAY -> {
                AppStackManager.finishAllActivity(Act_Main::class.java)
                presenter!!.setUncleCurrentItemIndex(1)
            }
            else -> {

            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        ForegroundBackgroundHelper.removeObserver(onForegroundBackgroundObserver)
    }
}